/*
 * @Author: lqx 1096345766@qq.com
 * @Date: 2025-04-01 10:28:17
 * @LastEditors: lqx 1096345766@qq.com
 * @LastEditTime: 2025-04-01 10:30:03
 * @FilePath: \payment-web\src\configs\request\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { get } from 'lodash-es'
import axios, { AxiosError } from 'axios'
import { toast } from '@/components/BasicToast'
import { storageTools } from '@/utils/storage'
import { StorageNameEnums } from '@/enums'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const request = axios.create({
  timeout: 60000, // 请求超时时间
  baseURL: import.meta.env.VITE_APP_BASE_API
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const tokenName = storageTools.getJSONLocalStorage(StorageNameEnums.TokenName)
    const tokenValue = storageTools.getJSONLocalStorage(StorageNameEnums.Token)
    //TODO: 登录token
    if (tokenName && tokenValue) {
      config.headers[tokenName] = tokenValue
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  ({ data, headers }) => {
    //检查返回的是否是文件流
    const contentType = headers['content-type']
    if (contentType && contentType.indexOf('application/json') === -1) {
      return data
    }

    const errCode = get(data, 'errCode')
    const respStatus = get(data, 'success', false)

    if (!respStatus) {
      switch (errCode) {
        case '401':
          toast.warning('登录已过期', '请重新登录')
          if (location.pathname !== '/login') {
            setTimeout(() => (location.href = '/login'), 1500)
          }
          return Promise.reject(data)
        case '403':
          toast.error(data.errMessage || '您没有权限访问该资源')
          return Promise.reject(data)
        default:
          toast.error(data.errMessage || '未知错误')
          return Promise.reject(data)
      }
    }

    return data
  },
  async (error: AxiosError) => {
    const { message } = error
    console.error('axios error ', error)
    toast.error(message)
    return Promise.reject(error)
  }
)

export default request
